package com.leyou.page.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    public Map<String, Object> loadItemData(Long id) {
        //查询spu
        SpuDTO spu = itemClient.querySpuById(id);
        //查询分类集合
        List<CategoryDTO> categories = itemClient.queryCategoryByIds(spu.getCategoryIds());
        //查询品牌
        BrandDTO brand = itemClient.queryBrandById(spu.getBrandId());
        //查询规格
        List<SpecGroupDTO> specs = itemClient.querySpecsByCid(spu.getCid3());
        //封装数据
        Map<String,Object> data = new HashMap<>();
        data.put("categories",categories);
        data.put("brand",brand);
        data.put("spuName",spu.getName());
        data.put("sunTitle",spu.getSubTitle());
        data.put("skus",spu.getSkus());
        data.put("detail",spu.getSpuDetail());
        data.put("specs",specs);
        return data;
    }

    @Autowired
    private SpringTemplateEngine templateEngine;

    private static final String BASE_DIR = "D:\\nginx-1.12.2\\nginx-1.12.2\\html\\item";

    public void createItemHtml(Long id){
        //1.准备上下文及模型数据
        Context context = new Context();
        context.setVariables(loadItemData(id));

        //2.准备目标文件路径
        File file = new File(BASE_DIR, id + ".html");

        //3.准备输出流，把渲染好的页面输出到nginx目录下
        try (PrintWriter writer = new PrintWriter(file, "UTF-8")) {
            templateEngine.process("item", context, writer);
        }catch (IOException e){
            log.error("生成静态页面异常，原因：{}",e.getMessage(),e);
        }
    }

    public void deleteItemHtml(Long id) {
        File file = new File(BASE_DIR, id + ".html");
        if (!file.exists()){
            if (!file.delete()){
                log.error("【静态页服务】静态页删除失败，商品id：{}", id);
                throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
            }
        }
    }
}
